import './style.css';
import { initCharts, updateChart, updateMetricValue, resizeCharts, metricsConfig } from './chart.js';
import { WebSocketManager } from './websocket.js';

// WebSocket配置
const WS_URL = 'ws://localhost:8888/api/ws';
const API_BASE_URL = 'http://localhost:8888/api';

// 初始化图表
const charts = initCharts();

// 创建WebSocket管理器
const wsManager = new WebSocketManager(WS_URL, {
    reconnectDelay: 5000,
    maxReconnectAttempts: Infinity
});
//timestamp
// 处理WebSocket消息
wsManager.onMessage((message) => {
    if (message.type === 'update' && message.data) {
       const data = message.data;
       let ts = message.timestamp
        
        // 更新所有指标
        Object.keys(metricsConfig).forEach(key => {
            const value = data[metricsConfig[key].key];
            if (value !== undefined) {
                updateChart(charts, key, value, ts);
                updateMetricValue(key, value);
            }
        });
    }
});

// 处理连接状态变化
wsManager.onStatusChange((isConnected) => {
    const statusEl = document.getElementById('connectionStatus');
    if (statusEl) {
        if (isConnected) {
            statusEl.textContent = '● 已连接';
            statusEl.className = 'connection-status connected';
        } else {
            statusEl.textContent = '● 连接断开';
            statusEl.className = 'connection-status disconnected';
        }
    }
});

// 窗口大小改变时重新调整图表
let resizeTimer;
window.addEventListener('resize', () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(() => {
        resizeCharts(charts);
    }, 200);
});

// 页面加载完成后连接WebSocket
window.addEventListener('load', () => {
    wsManager.connect();
    
    // 初始化配置弹窗事件
    initConfigModal();
});

// 页面关闭时清理
window.addEventListener('beforeunload', () => {
    wsManager.close();
});

// 初始化配置弹窗
function initConfigModal() {
    const modal = document.getElementById('configModal');
    const btn = document.getElementById('configButton');
    const span = document.getElementsByClassName('close')[0];
    const cancelBtn = document.getElementById('cancelConfig');
    const form = document.getElementById('drillConfigForm');
    
    // 点击配置按钮打开弹窗
    btn.onclick = function() {
        modal.style.display = 'block';
        loadCurrentConfig();
    };
    
    // 点击关闭按钮关闭弹窗
    span.onclick = function() {
        modal.style.display = 'none';
    };
    
    // 点击取消按钮关闭弹窗
    cancelBtn.onclick = function() {
        modal.style.display = 'none';
    };
    
    // 点击弹窗外部关闭弹窗
    window.onclick = function(event) {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    };
    
    // 处理表单提交
    form.onsubmit = function(event) {
        event.preventDefault();
        saveConfig();
    };
}

// 加载当前配置
async function loadCurrentConfig() {
    try {
        const response = await fetch(`${API_BASE_URL}/drill-config`);
        if (response.ok) {
            const config = await response.json();
            document.getElementById('d').value = config.d || '';
            document.getElementById('kn').value = config.kn || '';
            document.getElementById('kt').value = config.kt || '';
            document.getElementById('delta_p').value = config.delta_p || '';
        } else {
            console.error('获取配置失败:', response.status);
        }
    } catch (error) {
        console.error('加载配置时出错:', error);
    }
}

// 保存配置
async function saveConfig() {
    try {
        const config = {
            d: parseFloat(document.getElementById('d').value),
            kn: parseFloat(document.getElementById('kn').value),
            kt: parseFloat(document.getElementById('kt').value),
            delta_p: parseFloat(document.getElementById('delta_p').value),
            create_time: new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14),
            status: 1
        };
        
        const response = await fetch(`${API_BASE_URL}/drill-config/write`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(config)
        });
        
        if (response.ok) {
            alert('配置保存成功');
            document.getElementById('configModal').style.display = 'none';
        } else {
            const errorText = await response.text();
            alert(`保存配置失败: ${errorText}`);
        }
    } catch (error) {
        console.error('保存配置时出错:', error);
        alert(`保存配置时出错: ${error.message}`);
    }
}

// 导出给调试使用
if (import.meta.env.DEV) {
    window.__charts__ = charts;
    window.__wsManager__ = wsManager;
}